import http from './http'
import config from './config'
import loadExternalAssetMixin from './loadExternalAssetMixin'
var wx = require("weixin-js-sdk");

export default {

  /**
   * 获取Url参数
   * @param {*} url 
   * @returns 
   */
  getParams: (url) => {
    let formattedParams = {}
    let _arr = []
    location.href.split('#').map(u => {
      u.split('?').length > 1 && u.split('?')[1].split('&').map(m => {
        _arr.push(m)
      })
    })
    for (let i = 0; i < _arr.length; i++) {
      formattedParams[_arr[i].split('=')[0]] = _arr[i].split('=')[1]
    }
    return formattedParams
  },

  /**
   * @description 判断是不是微信浏览器
   * @param void
   * @returns void
   */
  isWeiXin: () => {
    var ua = window.navigator.userAgent.toLowerCase()
    if (ua.match(/MicroMessenger/i)) {
      if (ua.match(/MicroMessenger/i)[0] === 'micromessenger') {
        return true
      } else {
        return false
      }
    } else {
      return false
    }
  },

  /**
   * 格式化时间
   * @param {*} str 
   * @param {*} fmt 
   * @returns 
   */
  dateFormat: (str, fmt = 'YYYY-mm-dd') => {
    if (!str) {
      return ''
    }
    let date = new Date(str)
    let ret
    const opt = {
      "Y+": date.getFullYear().toString(), // 年
      "m+": (date.getMonth() + 1).toString(), // 月
      "d+": date.getDate().toString(), // 日
      "H+": date.getHours().toString(), // 时
      "M+": date.getMinutes().toString(), // 分
      "S+": date.getSeconds().toString() // 秒
      // 有其他格式化字符需求可以继续添加，必须转化成字符串
    };
    for (let k in opt) {
      ret = new RegExp("(" + k + ")").exec(fmt);
      if (ret) {
        fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
      }
    }
    return fmt;
  },

  initWxConfig: () => {
    loadExternalAssetMixin.methods.loadScript("https://res.wx.qq.com/open/js/jweixin-1.6.0.js", () => {
      http.get("/api/home/getUrlTicket", {
        url: encodeURIComponent(location.href.split('#')[0]),
      }).then((res) => {
        if (res.code == 1) {
          // 注入权限验证配置
          wx.config({
            debug: false,
            appId: res.data.appId,
            timestamp: res.data.timestamp,
            nonceStr: res.data.nonceStr,
            signature: res.data.signature,
            jsApiList: ["chooseImage", "uploadImage"],
          });
          wx.ready(function () { });
          wx.error(function (error) { });
        } else {
          this.$Message.error(res.msg);
        }
      });
    });
  },

  /**
   * 获取公用配置
   * @returns 
   */
  getGlobalConfig: () => {
    const level = http.get('/api/home/level')
    const subject = http.get('/api/home/subject')
    return new Promise(function (resolve, reject) {
      Promise.all([level, subject]).then(vals => {
        const [levelData, subjectData] = vals
        if (
          levelData.code == 1 && 
          subjectData.code == 1
        ) {
          config.level = levelData.data
          config.subject = subjectData.data
          resolve({
            level: levelData.data,
            subject: subjectData.data
          })
        } else {
          reject('error', levelData, subjectData)
        }
      })
    })
  },

  /**
   * 导出，将prarm拼接Url然后window.open()
   * @param {*} url 
   * @param {*} param 
   * @returns 
   */
  exportUrl: (url, param) => {
    const token = sessionStorage.getItem('LOGIN_INFO') ? JSON.parse(sessionStorage.getItem('LOGIN_INFO'))['token'] : ''
    let params = ''
    Object.keys(param).map(key => {
      params += `${key}=${param[key]}&`
    })
    params += `token=${token}`
    return config.Url + url + '?' + params
  },

  serverIdToPath: (serverid) => {
    return new Promise(function (reslove, reject) {
      http.get('/api/home/getFile', {
        serverId: serverid
      }).then(res => {
        if (res.code == 1) {
          reslove(res.data)
        } else {
          this.$Message.error(res.msg)
        }
      }).catch(err => {
        reject(err)
      })
    })
  },

}